package tsvetanv.inventory.util.validation;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import tsvetanv.inventory.model.Article;
import tsvetanv.inventory.model.Product;

/**
 * The ArticleValidator class realize business-logic validation of user input
 * for {@link Article} form. It uses as nested validater a
 * {@link ProductValidator}.
 * 
 * @author Tsvetan Vasilev
 * 
 */
public class ArticleValidator implements Validator {

	private ProductValidator productValidator;

	// private static Logger logger = Logger.getLogger(ArticleValidator.class);

	// --- Constructors, Getters, Setters --------------------------------------

	public void setProductValidator(ProductValidator productValidator) {
		this.productValidator = productValidator;
	}

	// --- Methods -------------------------------------------------------------

	public boolean supports(Class clazz) {
		return Article.class.isAssignableFrom(clazz);
	}

	/**
	 * Specifies custom business-logic validation on {@link Article}'s fields
	 * and includes nested {@link Product}'s validation .
	 */
	public void validate(Object target, Errors errors) {
		Article article = (Article) target;

		// validation on "Quantity" field to be required is done in initBind()
		// method of ArticleEditFormController

		// custom validation on "Quantity" field
		if (article.getQuantity() <= 0) {
			errors.rejectValue("quantity", "article.quantity.positive");
		}

		// validate Product nested object
		try {
			errors.pushNestedPath("product");
			ValidationUtils.invokeValidator(productValidator,
					article.getProduct(), errors);
		} finally {
			errors.popNestedPath();
		}
	}
}
